package com.focusai.efairy.ui.fragment;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.focusai.efairy.R;
import com.focusai.efairy.model.dev.DeviceItem;
import com.focusai.efairy.model.project.ProjectItem;
import com.focusai.efairy.model.request.GetDevListRequest;
import com.focusai.efairy.model.response.DevListResponse;
import com.focusai.efairy.network.HttpManager;
import com.focusai.efairy.network.Response;
import com.focusai.efairy.network.exception.NetworkException;
import com.focusai.efairy.ui.activity.dev.DevMapLocationActivity;
import com.focusai.efairy.ui.activity.dev.DeviceDetailInfoActivity;
import com.focusai.efairy.ui.activity.project.ProjectAddDeviceActivity;
import com.focusai.efairy.ui.adapter.DevListAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerAdapter;
import com.focusai.efairy.ui.adapter.base.BaseRecyclerViewHolder;
import com.focusai.efairy.ui.base.BaseFragment;
import com.focusai.efairy.ui.widget.PopWindowDevChatTypeView;
import com.focusai.efairy.ui.widget.SearchTittleView;
import com.focusai.efairy.ui.widget.TitleView;
import com.focusai.efairy.utils.Constants;

import java.util.ArrayList;

/**
 * Created by luo_guangwen on 2017/7/11.
 */

public class DevFragment extends BaseFragment implements PopWindowDevChatTypeView.OnViewItemClickLisenter {
    public static final String KEY_KEYWORD = "key_keyword";
    public static final String KEY_PROJECT_ITEM = "key_project_item";
    private TitleView mTitleView;
    private SearchTittleView searchTittleView;
    private RecyclerView mRecyclerView;
    private SwipeRefreshLayout layoutRefresh;
    private ImageView tipView;
    private DevListAdapter mAdapter;
    private ArrayList<DeviceItem> mList;
    private ArrayList<DeviceItem> mAllList;
    private boolean openInActivity = false;//在Activity内调用
    private ProjectItem projectItem = null; //项目Id
    private PopWindowDevChatTypeView mDevChatTypeView;

    public DevFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dev, container, false);
        initView(view);
        bindEvents();
        setDefaultValues();
        loadData("");
        return view;
    }

    @Override
    protected void initView(View view) {
        mRecyclerView = (RecyclerView) view.findViewById(R.id.rcyc_view);
        mTitleView = findView(view, R.id.title_view);
        layoutRefresh = findView(view, R.id.layout_refresh);
        searchTittleView = findView(view, R.id.view_tittle_search);
        tipView = findView(view,R.id.iv_no_data);
    }

    @Override
    protected void bindEvents() {
        if (getArguments() != null) {
            openInActivity = getArguments().getBoolean(KEY_KEYWORD, false);
            projectItem = (ProjectItem) getArguments().getSerializable(KEY_PROJECT_ITEM);
            if (projectItem != null) {
                mTitleView.getmBack().setVisibility(View.VISIBLE);
                mTitleView.getmBack().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getActivity().finish();
                    }
                });
            }
        }
        if (openInActivity) {
            mTitleView.getmTextRight().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getActivity(), DevMapLocationActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(DevMapLocationActivity.KEY_MAP_ITEMS, mList);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });
            mTitleView.getmTextRight1().setVisibility(View.VISIBLE);
            mTitleView.getmTextRight1().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openFilterWindow();
                }
            });
        } else {
            mTitleView.getmTextRight().setBackgroundDrawable(null);
            mTitleView.getmTextRight().setText(R.string.add);
            mTitleView.getmTextRight().setTextColor(getContext().getResources().getColor(R.color.main_color));
        }
        layoutRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadData("");
            }
        });
        searchTittleView.setSearchListener(new SearchTittleView.OnSearchListener() {
            @Override
            public void onStartQuery(String keywork, boolean hideInput) {
                if (hideInput) {
                    hideSoftInput();
                }
                loadData(keywork);
            }

            @Override
            public void onCancalBackClick() {
                mTitleView.setVisibility(View.VISIBLE);
                hideSoftInput();
                loadData("");
            }

            @Override
            public void onEnterInputKeyWork() {
                mTitleView.setVisibility(View.GONE);
            }
        });
    }

    @Override
    protected void setDefaultValues() {
        mList = new ArrayList<>();
        mAllList = new ArrayList<>();
        mAdapter = new DevListAdapter(getContext());
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        DividerItemDecoration itemDecoration = new DividerItemDecoration(getContext(), DividerItemDecoration.HORIZONTAL);
        itemDecoration.setDrawable(new ColorDrawable(getContext().getResources().getColor(R.color.general_grey_line)));
        mRecyclerView.addItemDecoration(itemDecoration);
        mAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseRecyclerViewHolder holder) {
                if (holder == null) return;
                int position = mRecyclerView.getChildLayoutPosition(holder.itemView);
                DeviceItem deviceItem = mList.get(position);
                Intent intent = new Intent(getActivity(), DeviceDetailInfoActivity.class);
                intent.putExtra(DeviceDetailInfoActivity.DEVICE_ITEM, deviceItem);
                startActivity(intent);
            }
        });
        mAdapter.setListener(new DevListAdapter.OnDevDetailClickListener() {
            @Override
            public void onDevDetailClickListener(DeviceItem item) {
                if (projectItem == null)
                    return;
                Intent intent = new Intent(mContext, ProjectAddDeviceActivity.class);
                intent.putExtra(ProjectAddDeviceActivity.KEY_DEVICE_ID, item.efairydevice_id + "");
                intent.putExtra(ProjectAddDeviceActivity.OPENTYPE, false);
                intent.putExtra(ProjectAddDeviceActivity.KEY_PROJECT_ID, projectItem.efairyproject_id+"");
                intent.putExtra(Constants.KEY_DETAIL, true);
                startActivity(intent);
            }
        });
    }

    private void loadData(String keyword) {
        String projectId = "";
        if (projectItem != null)
            projectId = projectItem.efairyproject_id + "";
        HttpManager.getInstance().sendRequest(new GetDevListRequest(keyword, projectId, new Response.Listener<DevListResponse>() {
            @Override
            protected void onSuccess(DevListResponse response) {
                layoutRefresh.setRefreshing(false);
                if (response == null && response.device_list != null)
                    return;
                mList.clear();
                mAllList.clear();
                mList.addAll(response.device_list);
                mAllList.addAll(mList);
                mAdapter.refreshData(mList);
                mDevChatTypeView = null;
                showTip();
            }

            @Override
            protected void onFail(NetworkException exception) {
                layoutRefresh.setRefreshing(false);
                doException(exception);
                showTip();
            }
        }));
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return searchTittleView.onKeyDown(keyCode, event);
    }

    /**
     * 打开过滤对话框
     */
    private void openFilterWindow() {
        if (mDevChatTypeView == null) {
            mDevChatTypeView = new PopWindowDevChatTypeView(getContext());
            mDevChatTypeView.setOnViewItemClickLisenter(this);
            mDevChatTypeView.setText();
        }
        mDevChatTypeView.show(mTitleView);
    }

    @Override
    public void onViewItemClick(int type) {
        switch (type) {
            case -1:
                mList.clear();
                mList.addAll(mAllList);
                mAdapter.notifyDataSetChanged();
                break;
            case 1:
                mList.clear();
                for (DeviceItem item : mAllList) {
                    if (item.efairydevice_alarm_id == 6 || item.efairydevice_alarm_id == 5) {
                        mList.add(item);
                    }
                }
                mAdapter.notifyDataSetChanged();
                break;
            case 2:
                mList.clear();
                for (DeviceItem item : mAllList) {
                    if (item.efairydevice_alarm_id == 0 || item.efairydevice_alarm_id == 3) {
                        mList.add(item);
                    }
                }
                mAdapter.notifyDataSetChanged();
                break;
            case 3:
                mList.clear();
                for (DeviceItem item : mAllList) {
                    if (item.efairydevice_alarm_id == 1 || item.efairydevice_alarm_id == 2 || item.efairydevice_alarm_id == 4) {
                        mList.add(item);
                    }
                }
                mAdapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }
    private void showTip(){
        if (mAdapter.getData() != null && mAdapter.getData().size() > 0){
            tipView.setVisibility(View.GONE);
        }else {
            tipView.setVisibility(View.VISIBLE);
        }
    }
}
